import React, { PureComponent,Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { getNodeByNameAndCallbackProcess } from '@/components/_utils/algorithmTools';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import {
  Table,
  Row,
  Col,
  Card,
  Form,
  Input,
	Icon,
	Button,
	message,
	Divider,
	Modal,
} from 'antd';
import {getValue} from '@/utils/globalcommon';
import {initTotalList} from '@/utils/globalcommon';
import styles from './ProMenuAuthList.less';

import CreateForm from './ProMenuAuthCreateForm';//新增菜单
import UpdateForm from './ProMenuAuthUpdateForm';//修改菜单
import ViewForm from './ProMenuAuthViewForm';//查看菜单
import MenuAuthTree from './ProMenuAuthTree';//菜单树

import ProAuthorityCreateForm  from './ProAuthorityCreateForm'; //新增角色
import ProAuthorityUpdateForm from './ProAuthorityUpdateForm'; //修改角色
import ProAuthorityViewForm  from './ProAuthorityViewForm'; //查看角色
const FormItem = Form.Item;
const { confirm } = Modal;

//角色列表

class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };
  
  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      type: "radio",
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable} style={{float: 'left',width:'70%'}}>
        <Table
          rowKey={rowKey || 'id' || 'key'}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
          size="middle"
        />
      </div>
    );
  }
}

@connect(({ promenuauth, loading }) => ({
    promenuauth,
    loading: loading.models.promenuauth,
}))
@Form.create()
class ProMenuAuthList extends PureComponent {
		state = {
        modalVisible: false,
        updateModalVisible: false,
        viewModalVisible: false,
        expandForm: false,
        selectedRows: [],
        formValues: {},
        updateFormValues: {},
        viewFormValues: {},
        authId:[],
        menuTree:[],
        root_parentid:'000000000000',
        addMenuTreeInfo:[],
        
        modalVisibleByAuth: false,
		    updateModalVisibleByAuth: false,
		    viewModalVisibleByAuth: false,
		    updateFormValuesByAuth: {},
        viewFormValuesByAuth: {},
        
        currentPage: 1,
        pageSize: 10,
        checkedKeys:[],
        
        addButtonVisible: 0,
        updateButtonVisible: 0,
        deleteButtonVisible: 0,
    };

  columns = [

    {
      title: '名称',
      dataIndex: 'auth_name',
      key: 'auth_name',
    }, {
      title: '类型',
      dataIndex: 'auth_type',
      key: 'auth_type',
    }, {
      title: '级别',
      dataIndex: 'auth_level',
      key: 'auth_level',
    }, {
      title: '描述',
      dataIndex: 'auth_description',
      key: 'auth_description',
    },{
      title: '操作',
      align: 'center',
      render: (text, record) => {
	        	const { updateButtonVisible,deleteButtonVisible } = this.state;
	        	return (
		        	<Fragment>
								{/*<a onClick={() => this.handleViewModalVisibleByAuth(true, record)}>查看</a>
								<Divider type="vertical" />
							    {updateButtonVisible == 1?(
							    	<span><a onClick={() => this.handleUpdateModalVisibleByAuth(true, record)}>编辑</a>
							    	<Divider type="vertical" /></span>
							    	
							    ):null}
							    {deleteButtonVisible == 1?(
							    	<a onClick={() => this.handleDeleteRecordByAuth(record)}>删除</a>
							    ):null}*/}
							    
									{updateButtonVisible == 1?(
							    	<Button  type="primary"  icon="edit" style={{marginRight: '5px'}} onClick={() => this.handleUpdateModalVisibleByAuth(true, record)}></Button>
							    ):null}
							    {deleteButtonVisible == 1?(
							    	<Button  type="danger" icon="delete" onClick={() => this.handleDeleteRecordByAuth(record)}></Button>
							    ):null}
						    
					    </Fragment>
	          );
	    }
    },
  ];

  constructor(props) {
    super(props);
  }

  componentDidMount() {
  		const { dispatch } = this.props;
			dispatch({
		      type: 'promenuauth/query_page_for_proauthority',
		      payload: {
		    		currentPage: 1,
		       	pageSize: 10,
		    	}
	    });
	    dispatch({
	        type: 'promenuauth/get_promenutree_by_levelcode',
	        payload:{
	        	parentid:this.state.root_parentid
	        }
	    });
  		if(localStorage.getItem('auth_button') == "undefined") return false;
  		const authButton = JSON.parse(localStorage.getItem('auth_button'));
			getNodeByNameAndCallbackProcess(authButton,"proauthority",(item,index,arr) => {
	    	if(item.children) {
		    		item.children.map((item,index) => {
		    			if(item.button_type == "add") {
		    				this.setState({
		    					addButtonVisible: 1,
		    				})
		    			}else if(item.button_type == "update") {
		    				this.setState({
		    					updateButtonVisible: 1,
		    				})
		    			}else if(item.button_type == "delete") {
		    				this.setState({
		    					deleteButtonVisible: 1,
		    				})
		    			}
		    		})
	    	}
	    })

  }
  
  componentWillReceiveProps(nextProps) {
  	console.log(nextProps.promenuauth.checkedKeysByAuth);
		if(undefined != nextProps.promenuauth.checkedKeysByAuth && nextProps.promenuauth.checkedKeysByAuth.list !== this.props.promenuauth.checkedKeys.list) {
	      this.setState({checkedKeys: nextProps.promenuauth.checkedKeysByAuth});
		}

	}

handleModalVisible = (flag,record) => {
    this.setState({
        modalVisible: !!flag,
        addMenuTreeInfo: record || {},
    });
};

handleUpdateModalVisible = (flag, record) => {
    this.setState({
        updateModalVisible: !!flag,
        updateFormValues: record || {},
    });
};

handleViewModalVisible = (flag, record) => {
    this.setState({
        viewModalVisible: !!flag,
        viewFormValues: record || {},
    });
};

handleAdd = fields => {
    const { dispatch } = this.props;
    const { key,levelcode } = this.state.addMenuTreeInfo;
    dispatch({
        type: 'promenuauth/insert_for_promenu',
        payload: {
        		type: fields.type,
        		button_type: "",
        		root_parentid:this.state.root_parentid,
            text: fields.text,
            parentid: key,
            levelcode: levelcode,
            href: fields.href,
            component: fields.component,
            i18n_name: fields.i18n_name,
            enable: fields.enable,
            redirect: fields.redirect,
            hideInMenu: fields.hideInMenu,
            icon: fields.icon,
        },
    });

    message.success('添加成功');
    this.handleModalVisible();
};

handleUpdate = fields => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
        type: 'promenuauth/update_for_promenu',
        payload: {
        		root_parentid:this.state.root_parentid,
            recordid: fields.recordid,
            id: fields.id,
            text: fields.text,
            parentid: fields.parentid,
            levelcode: fields.levelcode,
            href: fields.href,
            component: fields.component,
            i18n_name: fields.i18n_name,
            enable: fields.enable,
            redirect: fields.redirect,
            icon: fields.icon,
            hideInMenu: fields.hideInMenu,
        },
    });

    message.success('修改成功');
    this.handleUpdateModalVisible();

};

handleDeleteRecord = record => {
    const { dispatch } = this.props;
    const { root_parentid } = this.state;  
    confirm({
	    title: '您确定要删除此菜单项吗?',
	    okText: '确认',
	    cancelText: '取消',
	    onOk() {
	        dispatch({
		        type: 'promenuauth/delete_by_primary_key_for_promenu',
		        payload: {
        			root_parentid:root_parentid,
        			recordid: record.recordid,
		        },
		        callback: (res) => {
		        	if(res.success) {
		    				message.success('删除成功');
		        	}else {
		        		message.success('删除失败');
		        	}
		        }
	        });
	    },
	    onCancel() {},
	  });
        
};



handleModalVisibleByAuth = flag => {
    this.setState({
      modalVisibleByAuth: !!flag,
    });
};

handleUpdateModalVisibleByAuth = (flag, record) => {
    this.setState({
      updateModalVisibleByAuth: !!flag,
      updateFormValuesByAuth: record || {},
    });
};

handleViewModalVisibleByAuth = (flag, record) => {
    this.setState({
      viewModalVisibleByAuth: !!flag,
      viewFormValuesByAuth: record || {},
    });
};

  handleAddByAuth = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'promenuauth/insert_for_proauthority',
      payload: {
        auth_id: fields.auth_id,
        auth_name: fields.auth_name,
        auth_type: fields.auth_type,
        auth_description: fields.auth_description,
        auth_level: fields.auth_level,
        display: fields.display,
        note: fields.note,
        is_system_auth: fields.is_system_auth,
        creator_id: fields.creator_id,
        parent_id: fields.parent_id,
      },
      callback: (res) => {
	    	if(res.success) {
					message.success('添加成功');
	    	}else {
	    		message.success('添加失败');
	    	}
	    }
    });
    
		this.setState({
			currentPage: 1,
			selectedRows: [],
			menuTree:[],
			authId:[],
			checkedKeys:[],
		})
		
    this.handleModalVisibleByAuth();

  };

  handleUpdateByAuth = fields => {

    const { dispatch } = this.props;
    const { currentPage,pageSize } = this.state;
    dispatch({
	      type: 'promenuauth/update_for_proauthority',
	      payload: {
	        auth_id: fields.auth_id,
	        auth_name: fields.auth_name,
	        auth_type: fields.auth_type,
	        auth_description: fields.auth_description,
	        auth_level: fields.auth_level,
	        display: fields.display,
	        note: fields.note,
	        is_system_auth: fields.is_system_auth,
	        creator_id: fields.creator_id,
	        parent_id: fields.parent_id,
	        currentPage,
        	pageSize,
	      },
	      callback: (res) => {
		    	if(res.success) {
						message.success('修改成功');
		    	}else {
		    		message.success('修改失败');
		    	}
		    }
    });

    this.setState({
			selectedRows: [],
			menuTree:[],
			authId:[],
			checkedKeys:[],
		})
    this.handleUpdateModalVisibleByAuth();

  };

  handleDeleteRecordByAuth = record => {
    const { dispatch } = this.props;
		const { currentPage,pageSize } = this.state;
		confirm({
		    title: '您确定要删除此角色吗?',
		    okText: '确认',
		    cancelText: '取消',
		    onOk() {
		        dispatch({
			        type: 'promenuauth/delete_by_primarykey_for_proauthority',
			        payload: {
		        		recordid: record.auth_id,
		        		currentPage,
	        			pageSize,
			        },
			        callback: (res) => {
			        	if(res.success) {
			    				message.success('删除成功');
			        	}else {
			        		message.success('删除失败');
			        	}
			        }
		        });
		    },
		    onCancel() {},
	  });

};



toggleForm = () => {
    const { expandForm } = this.state;
    
    this.setState((state,props) => ({
    	expandForm: !state.expandForm,
    }))
};

handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
        formValues: {},
        currentPage: 1,
				selectedRows: [],
				menuTree:[],
				authId:[],
				checkedKeys:[],
    });
    dispatch({
        type: 'promenuauth/query_page_for_proauthority',
        payload: {},
    });
};


handleSearch = e => {
    e.preventDefault();
    
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
        if (err) return;

		    const values = {
		        ...fieldsValue,
		        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
		    };
		
		    this.setState({
		       	currentPage: 1,
						selectedRows: [],
						menuTree:[],
						authId:[],
						checkedKeys:[],
						
						formValues: values,
		    });
		
		    dispatch({
		        type: 'promenuauth/query_page_for_proauthority',
		        payload: values,
		    });
		});
};

handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
		this.setState({
			currentPage: pagination.current,
      pageSize: pagination.pageSize,
			selectedRows: [],
			menuTree:[],
			authId:[],
			checkedKeys:[],
		})

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
		    const newObj = { ...obj };
		    newObj[key] = getValue(filtersArg[key]);
		    return newObj;
		}, {});
		
    const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...formValues,
        ...filters,
    };
    
    if (sorter.field) {
        params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
        type: 'promenuauth/query_page_for_proauthority',
        payload: params,
    });
};


handleSelectRows = rows => {
   	const authIdArray = new Array(); 
  	const { dispatch } = this.props;
  	rows.map(item => {
			authIdArray.push(item.auth_id);
			return authIdArray
		})
  	this.setState({
        selectedRows: rows,
        authId: authIdArray
   	});
		dispatch({
	        type: 'promenuauth/get_all_menutree_by_authid', 
	        payload: {
	  			auth_id:authIdArray
	        }, 
	        callback:(response) => {
	        	this.setState({
		    			menuTree: response.list
		    		}) 
	        }
	 	});
		dispatch({
	        type: 'promenuauth/get_all_menutree_by_authid_for_deletetree', 
	        payload: {
	  				auth_id:authIdArray
	        }
	 	});
};

checkedTreeChild = checkedInfo => {
	console.log(checkedInfo);
	
	const checkedTree = checkedInfo.checkedNodes;
	const checkedTreeParent = checkedInfo.halfCheckedKeys;
	const checkedKeyArray = new Array();
	checkedTree.map(item => {
		checkedKeyArray.push(item.props.dataRef.key)
		return checkedKeyArray;
	})
	checkedTreeParent.map(item => {
		if(item != "000000000000") {
			checkedKeyArray.push(item);
		}
		return checkedKeyArray;
	})
	this.setState({
		menuTree:checkedKeyArray
	})
}

handleMenuAuthSave = () => {
	const { authId,menuTree} = this.state;
	const { dispatch } = this.props;
	if(!authId || authId.length == 0 ) {
		message.warning("请选择要授权的角色!!!");
		return false;
	}
	const menuTreeAuth = new Array();
	const authIds = new Array();
	for(let i = 0;i < authId.length;i++) {
		authIds.push({
			id: authId[i]
		})
		for(let j = 0;j < menuTree.length;j++) {
			menuTreeAuth.push({
				auth_id: authId[i],
				menu_id: menuTree[j],
			})
		}
	}
	dispatch({
    type: 'promenuauth/insert_batch_for_promenuauth',
    payload: {
    	authids:authIds,
    	authids_menuids: menuTreeAuth,
    	currentPage: this.state.currentPage,
    	pageSize: 10,
    },
  });
  message.success('授权成功');
}

renderAdvancedForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
	        	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
							<Col md={8} sm={24}>
					        <FormItem label="角色名称">
					        	{getFieldDecorator('auth_name')(<Input placeholder="请输入" />)}
									</FormItem>
				    	</Col>
							<Col md={8} sm={24}>
					        <FormItem label="角色类型">
					        	{getFieldDecorator('auth_type')(<Input placeholder="请输入" />)}
									</FormItem>
				    	</Col>
				    	<Col md={8} sm={24}>
					        <span className={styles.submitButtons}>
						        <Button type="primary" htmlType="submit">
						        查询
						        </Button>
						        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
						        重置
						        </Button>
						        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
						        收起 <Icon type="up" />
						        </a>
					        </span>
					    </Col>
	    			</Row>
        </Form>
	);
}

renderSimpleForm() {
    const {
        form: { getFieldDecorator },
    } = this.props;
    return (
        <Form onSubmit={this.handleSearch} layout="inline">
        	<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
						<Col md={8} sm={24}>
				    		<FormItem label="角色名称">
				        	{getFieldDecorator('auth_name')(<Input placeholder="请输入" />)}
								</FormItem>
						</Col>
	    			<Col md={8} sm={24}>
				        <FormItem label="角色类型">
				        	{getFieldDecorator('auth_type')(<Input placeholder="请输入" />)}
								</FormItem>
			    	</Col>
				    <Col md={8} sm={24}>
				        <span className={styles.submitButtons}>
					        <Button type="primary" htmlType="submit">
					        查询
					        </Button>
					        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
					        重置
					        </Button>
					        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
					        展开 <Icon type="down" />
					        </a>
				        </span>
				    </Col>
        	</Row>
        </Form>
	);
}

    renderForm() {
        const { expandForm } = this.state;
        return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
    }
  render() {
  	const {
        promenuauth: { data,menu },
        loading,
    } = this.props;

        
    const { 
    	selectedRows, 
    	modalVisible, 
    	updateModalVisible, 
    	viewModalVisible,  
    	updateFormValues,  
    	viewFormValues,
    	menuTree,
    	menuTreeInfo,
    	addMenuTreeInfo,
    	
    	modalVisibleByAuth, 
    	updateModalVisibleByAuth, 
    	viewModalVisibleByAuth,  
    	updateFormValuesByAuth,  
    	viewFormValuesByAuth,
    	checkedKeys,
    	addButtonVisible,
    } = this.state;
   	const parentMethods = {
       handleAdd: this.handleAdd,
       handleModalVisible: this.handleModalVisible,
       addMenuTreeInfo: addMenuTreeInfo
    };
    
   	const parentRole = {
       	selectedRows: selectedRows,
       	checkedKeys: checkedKeys,
       	handleModalVisible: this.handleModalVisible,
       	handleUpdateModalVisible: this.handleUpdateModalVisible,
       	handleViewModalVisible: this.handleViewModalVisible,
       	handleDeleteRecord: this.handleDeleteRecord,
       	checkedTreeChild: this.checkedTreeChild,
       	dispatch: this.props.dispatch,
    };
    
    const updateMethods = {
        handleUpdateModalVisible: this.handleUpdateModalVisible,
        handleUpdate: this.handleUpdate,
    };
    
    const viewMethods = {
        handleViewModalVisible: this.handleViewModalVisible,
    };
    
    const parentMethodsByAuth = {
      handleAddByAuth: this.handleAddByAuth,
      handleModalVisibleByAuth: this.handleModalVisibleByAuth,
    };
    
    const updateMethodsByAuth = {
      handleUpdateModalVisibleByAuth: this.handleUpdateModalVisibleByAuth,
      handleUpdateByAuth: this.handleUpdateByAuth,
    };
    
    const viewMethodsByAuth = {
      handleViewModalVisibleByAuth: this.handleViewModalVisibleByAuth,
    };
    return (
        <PageHeaderWrapper title="角色信息列表">
            <Card bordered={false}>
		            <div className={styles.proMenutableList} style={{position:'relative'}}>
		            <div className={styles.proMenutableListForm}>{this.renderForm()}</div>
		            <div className={styles.proMenutableListOperator}>
                		{addButtonVisible == 1?(
					            <Button icon="plus" type="primary" onClick={() => this.handleModalVisibleByAuth(true)}>
					        		新增
					        		</Button>
					        	):<div style={{height: '32px',display:"inline-block"}}></div>}
				        		<Button type="primary" style={{float: 'right'}} onClick={ this.handleMenuAuthSave }>
				        			菜单分配
				        		</Button>
		    				</div>
				    		<StandardTable
				        rowKey={"auth_id"}
				        selectedRows={selectedRows}
				        loading={loading}
				        data={data}
				        columns={this.columns}
				        onSelectRow={this.handleSelectRows}
				        onChange={this.handleStandardTableChange}/>
				        {menu && Object.keys(menu).length ? (
				        	<MenuAuthTree {...parentRole} menu={menu}/>
				        ) : null}
				    		</div>
		        </Card>
		        <CreateForm {...parentMethods} modalVisible={modalVisible} />
		        <ProAuthorityCreateForm {...parentMethodsByAuth} modalVisibleByAuth={modalVisibleByAuth} />
						{updateFormValues && Object.keys(updateFormValues).length ? (
		            <UpdateForm
		            {...updateMethods}
		            updateModalVisible={updateModalVisible}
		            values={updateFormValues}
		            />
		        ) : null}
						{updateFormValuesByAuth && Object.keys(updateFormValuesByAuth).length ? (
		            <ProAuthorityUpdateForm
		            {...updateMethodsByAuth}
		            updateModalVisibleByAuth={updateModalVisibleByAuth}
		            values={updateFormValuesByAuth}
		            />
		        ) : null}
						{viewFormValues && Object.keys(viewFormValues).length ? (
		            <ViewForm
		            {...viewMethods}
		            viewModalVisible={viewModalVisible}
		            values={viewFormValues}
		            />
		        ) : null}
						{viewFormValuesByAuth && Object.keys(viewFormValuesByAuth).length ? (
		            <ProAuthorityViewForm
		            {...viewMethodsByAuth}
		            viewModalVisibleByAuth={viewModalVisibleByAuth}
		            values={viewFormValuesByAuth}
		            />
		        ) : null}
    	</PageHeaderWrapper>
    );
  }
}

export default ProMenuAuthList;
